package com.chen.controller;

import com.chen.constant.MessageConstant;
import com.chen.entity.Result;
import com.chen.pojo.Setmeal;
import com.chen.service.SetmealService;
import com.chen.utils.QiNiuUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * @Author zhebie
 * @DATE 2021/9/19
 */
@RestController()
@RequestMapping("/setmeal")
public class SetmealController {
    private static final Logger log = LoggerFactory.getLogger(SetmealController.class);

    @Autowired
    private SetmealService setmealService;

    /**
     * 添加套餐上传时的照片
     * @param imgFile
     * @return
     */
    @PostMapping("/upload")
    public Result upload(MultipartFile imgFile){
        //获取源文件名
        String filename = imgFile.getOriginalFilename();
        //获取后缀名
        String suffix = filename.substring(filename.lastIndexOf("."));
        //生成唯一文件名
        String imgName = UUID.randomUUID().toString() + suffix;
        try {
            //调用七牛云工具上传文件
            QiNiuUtils.uploadViaByte(imgFile.getBytes(),imgName);
            //构建Map
            Map<String,String> resultMap = new HashMap<String,String>();
            //两个key：domain，imgName  返回给前端
            resultMap.put("domain",QiNiuUtils.DOMAIN);
            resultMap.put("imgName",imgName);
            //返回Result
            return new Result(true, MessageConstant.PIC_UPLOAD_SUCCESS,resultMap);
        } catch (IOException e) {
            log.error("上传文件失败",e);
            return new Result(false,MessageConstant.PIC_UPLOAD_FAIL);
        }
    }

    /**
     * 添加套餐提交
     * @param setmeal
     * @param
     * @return
     */
    @PostMapping("/add")
    public Result add(@RequestBody Setmeal setmeal,@RequestParam List<Integer> checkgroupIds){
        //调用业务添加套餐
        setmealService.add(setmeal,checkgroupIds);
        //返回操作的结果
        return new Result(true,MessageConstant.ADD_SETMEAL_SUCCESS);
    }
}
